package com.yequan;

import org.apache.commons.lang3.StringUtils;

/**
 * 车牌号脱敏
 *
 * @author yequan
 * @date 2020/12/09 16:26
 **/
public class NumberMask {

    /**
     * 车牌号脱敏, 保留前两位和后两位, 中间使用*号代替, 津QD5815 --> 津Q***15
     */
    public static String plateNumberMask1(String plateNumber) {
        if (StringUtils.isBlank(plateNumber)) {
            return plateNumber;
        }
        String endNumber = StringUtils.substring(plateNumber, -2);
        String beginNumber = StringUtils.substring(plateNumber, 0, 2);
        String midnNumber = StringUtils.substring(plateNumber, 2, -2).trim().replaceAll("[a-zA-Z0-9]", "*");
        return new StringBuilder(beginNumber).append(midnNumber).append(endNumber).toString();
    }

    /**
     * 车牌号脱敏， 只保留后三位  京A12345 --->  ***345
     *
     * @param plateNumber
     * @return
     */
    public static String plateNumberMask2(String plateNumber) {
        if (StringUtils.isBlank(plateNumber)) {
            return plateNumber;
        }
        String endNumber = StringUtils.substring(plateNumber, -3);
        int i = plateNumber.lastIndexOf(endNumber);
        String startNumber = plateNumber.substring(0, i);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i1 = 0; i1 < startNumber.length(); i1++) {
            stringBuilder.append("*");
        }
        return plateNumber.replace(startNumber, stringBuilder.toString());
    }

    public static String plateNumberMask3(String plateNumber) {
        if (StringUtils.isBlank(plateNumber)) {
            return plateNumber;
        }
        int len = plateNumber.length() - 3;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            stringBuilder.append("*");
        }
        return plateNumber.replaceAll(".{" + len + "}", stringBuilder.toString());
    }

    public static void main(String[] args) {
        String n1 = "京A123456";
        String n2 = "京A12345";

        System.out.println(plateNumberMask3(n1));
        System.out.println(plateNumberMask3(n2));
    }

}
